package com.mier.android.fbtalksms;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;










import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphMultiResult;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.model.GraphPlace;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;
import com.mier.android.fbtalksms.adapter.FBFriends;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class FBFriendsListActivity extends Activity {
	private static List<FBFriends> friendsList;
	private static String App_Id = "196742477082115";
	private List<GraphUser> graphUser = new ArrayList<GraphUser>();
	private Session.StatusCallback sessionCallback = new SessionStatusCallback();
	private ListView friendListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fbfriends_activity);
		if(android.os.Build.VERSION.SDK_INT > 9){
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		if(isNetworkAvailable()){
			Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
			Session session = Session.getActiveSession();
			if (session == null) {
				if (savedInstanceState != null) {
					session = Session.restoreSession(this, null, sessionCallback,
							savedInstanceState);
				}
				if (session == null) {
					session = new Session(this);
				}
				Session.setActiveSession(session);
				if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
					session.openForRead(new Session.OpenRequest(this)
							.setCallback(sessionCallback));
				}
			}
			updateView();
		} else {
			AlertDialog alert = new AlertDialog.Builder(this).create();
			alert.setTitle("Network Problem");
			alert.setMessage("No Internet Connection Available");
			alert.setButton("Close", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
				  Intent intent = new Intent(getApplicationContext(), MainActivity.class);
				  startActivity(intent);
				}
			});
			alert.show();
		}
	}
	
	public boolean isNetworkAvailable(){
		ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		
		return info!=null && info.isConnected();
		
	}

	@Override
	public void onStart() {
		super.onStart();
		Session.getActiveSession().addCallback(sessionCallback);
	}

	@Override
	public void onStop() {
		super.onStop();
		Session.getActiveSession().removeCallback(sessionCallback);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Session session = Session.getActiveSession();
		Session.saveSession(session, outState);
	}

	
	
	public ListView getListView(){
		return friendListView;
	}

	public class SessionStatusCallback implements Session.StatusCallback {

		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			updateView();
		}

	}
	
    public void updateView(){
    	String fql = "SELECT name,uid FROM user WHERE online_presence IN ('active', 'idle') AND uid IN ( SELECT uid2 FROM friend WHERE uid1 = me())";
		List<String> permission = new ArrayList<String>();
		permission.add("email");
		permission.add("publish_stream");
		permission.add("user_status");
		permission.add("user_online_presence");
		permission.add("friends_online_presence");
		Session session = Session.getActiveSession();
		if (session.isOpened()) {
			List<String> permissions = session.getPermissions();
			for (int i = 0; i < permissions.size(); i++) {
				Log.d("com.mier.android.FBFriendsListActivity",
						permissions.get(i));
			}

			// session.requestNewPublishPermissions(new
			// NewPermissionsRequest(this,permission));
			Bundle bundle = new Bundle();
			bundle.putString("q", fql);
//			Request request = new Request(session, graphPath, parameters, httpMethod)
			Request request = new Request(Session.getActiveSession(), "/fql", bundle, HttpMethod.GET , new RequestSessionCallback());
			Request.executeBatchAsync(request);
		} else {
			if (!session.isOpened() && !session.isClosed()) {
				session.openForRead(new Session.OpenRequest(this).setCallback(sessionCallback));
			} else {
				Session.openActiveSession(this, true,
						sessionCallback);
			}
		}
    }
    
    public class RequestSessionCallback implements Request.Callback{

		@Override
		public void onCompleted(Response response) {
			try {
//				System.out.println(response);
				GraphMultiResult result = response.getGraphObjectAs(GraphMultiResult.class);
				
				GraphObjectList<GraphObject> gObjList = result.getData();
				graphUser = gObjList.castToListOf(GraphUser.class);
//				graphUser = users;
				
//				ListView listView = friendListView ;
				ListView friendListView = (ListView) findViewById(R.id.ListFBFriendsView);
				friendListView.setVisibility(View.VISIBLE);
				ArrayAdapter<GraphUser> adapter = new FbFriendsAdapter(graphUser);
				friendListView.setAdapter(adapter);
				

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

		

	}
    
    
    
    public class FbFriendsAdapter extends ArrayAdapter<GraphUser> {
		List<GraphUser> fbfriends;
		
		public FbFriendsAdapter(List<GraphUser> friends){
			super(getApplicationContext(), R.layout.fbfriends_list, friends);
			this.fbfriends = friends;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return fbfriends.size();
		}

		@Override
		public GraphUser getItem(int position) {
			// TODO Auto-generated method stub
			return fbfriends.get(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View listView = convertView;
			if (listView == null) {
				listView = getLayoutInflater().inflate(R.layout.fbfriends_list,
						parent, false);
			}
			TextView name = (TextView) listView.findViewById(R.id.fbName);
			name.setText(fbfriends.get(position).getName());
			Map<String, Object> map = fbfriends.get(position).asMap();
			String id=null;
			if(map.containsKey("uid")){
				id = map.get("uid").toString();
			}
			ProfilePictureView imgView = (ProfilePictureView) listView.findViewById(R.id.fbProfile);
			imgView.setProfileId(id);
//			String url = "http://graph.facebook.com/" + id +"/picture?type=small";
//			ImageView imgView = (ImageView) listView.findViewById(R.id.fbProfile);
//			imgView.setTag(url);
//			new FriendsListLoader().execute(imgView);
			
			return listView;
		}

	}

}
